<?php
use \think\facade\Db;
// 这是系统自动生成的公共文件

// 获得分诶下文档数量 -- wf添加
function catecount($cateid) {
    $where[] = array('cid','=',$cateid);
    $where[] = array('del_status','=',1);
    $data = Db::name('doc_con')->where($where)->count();
    return $data;
}


function useritemid($uid, $typeid,$type=2) { //用户收藏的id集合
    $where[] = array('typeid','=',$typeid);
    $where[] = array('type','=',$type);
    $where[] = array('uid','=',$uid);
    $data = Db::name('itemlog')->where($where)->field('itemid')->select()->toArray();
//    $data = array_unique($data);
    $arr = [];
    foreach ($data as $k=>$v){
        $arr[$k]=$v['itemid'];
    }
    $arr = array_unique($arr);
    return $arr;
}



function getuserscore($uid) {
    $map['uid'] = $uid;
    $data = Db::name('user_scoresum')->where($map)->value('score');
    if ($data == '') {
        $data1['uid'] = $uid;
        Db::name('user_scoresum')->save($data1);
        $data = 0;
    }
    return $data;
}

function similardoc($id, $num) {
    $map1['id'] = $id;
    $tags = Db::name('doc_con')->where($map1)->value('tags');
    $tagarr = explode(',', $tags);
    foreach ($tagarr as $key => $value) {
        $tagarr[$key] = '%' . $value . '%';
    }
    $where[] =array('title','like',$tagarr);
    $where[] =array('id','<>',$id);
    $data = Db::name('doc_con')->whereOR($where)->limit($num)->select();
    return $data;
}
//同分类热门文档
function samecatedoc($id) {
    $map['id'] = $id;
    $cateid = Db::name('doc_con')->where($map)->value('cid');
    $where[] =array('id','<>',$id);
    $where[] =array('cid','=',$cateid);
    $data = Db::name('doc_con')->where($where)->order('hits desc')->select();
    return $data;
}


/**
 * 友好时间
 */
function fdate($time) {
    if (!$time) return false;
    $fdate = '';
    $d = time() - intval($time);
    $ld = $time - mktime(0, 0, 0, 0, 0, date('Y')); //年
    $md = $time - mktime(0, 0, 0, date('m'), 0, date('Y')); //月
    $byd = $time - mktime(0, 0, 0, date('m'), date('d') - 2, date('Y')); //前天
    $yd = $time - mktime(0, 0, 0, date('m'), date('d') - 1, date('Y')); //昨天
    $dd = $time - mktime(0, 0, 0, date('m'), date('d'), date('Y')); //今天
    $td = $time - mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')); //明天
    $atd = $time - mktime(0, 0, 0, date('m'), date('d') + 2, date('Y')); //后天
    if ($d == 0) {
        $fdate = '刚刚';
    } else {
        switch ($d) {
            case $d < $atd:
                $fdate = date('Y年m月d日', $time);
                break;
            case $d < $td:
                $fdate = '后天' . date('H:i', $time);
                break;
            case $d < 0:
                $fdate = '明天' . date('H:i', $time);
                break;
            case $d < 60:
                $fdate = $d . '秒前';
                break;
            case $d < 3600:
                $fdate = floor($d / 60) . '分钟前';
                break;
            case $d < $dd:
                $fdate = floor($d / 3600) . '小时前';
                break;
            case $d < $yd:
                $fdate = '昨天' . date('H:i', $time);
                break;
            case $d < $byd:
                $fdate = '前天' . date('H:i', $time);
                break;
            case $d < $md:
                $fdate = date('m月d H:i', $time);
                break;
            case $d < $ld:
                $fdate = date('m月d', $time);
                break;
            default:
                $fdate = date('Y年m月d日', $time);
                break;
        }
    }
    return $fdate;
}


 function getDocLists($tag=[])
{
    $tag['field'] = isset($tag['field']) ? trim($tag['field']) : '*';
    $tag['where'] = isset($tag['where']) ? trim($tag['where']) : '';
    $tag['cateid'] = isset($tag['cateid']) ? trim($tag['cateid']) : 0;
    $tag['order'] = isset($tag['order']) ? trim($tag['order']) : 'id DESC';
    $tag['day'] = isset($tag['day']) ? intval($tag['day']) : 0;
    $tag['cache'] = isset($tag['cache']) ? intval($tag['cache']) : 60;
    $tag['pagenum'] = isset($tag['pagenum']) ? intval($tag['pagenum']) : 0;
    $tag['minscore'] = isset($tag['minscore']) ? trim($tag['minscore']) : 'min';
    $tag['maxscore'] = isset($tag['maxscore']) ? trim($tag['maxscore']) : 'max';
    $tag['ext'] = isset($tag['ext']) ? trim($tag['ext']) : 0;
    $tag['usertype'] = isset($tag['usertype']) ? trim($tag['usertype']) : 0;
    $tag['uid'] = isset($tag['uid']) ? intval($tag['uid']) : 0;
    $tag['own'] = isset($tag['own']) ? intval($tag['own']) : 0;//为1时表示调用该uid的文档
    $tag['how'] = isset($tag['how']) ? trim($tag['how']) : '';
    $tag['search'] = isset($tag['search']) ? trim($tag['search']) : '';
    $tag['similar'] = isset($tag['similar']) ? trim($tag['similar']) : 0;
    $tag['top'] = isset($tag['top']) ? trim($tag['top']) : 0;
    $tag['choice'] = isset($tag['choice']) ? trim($tag['choice']) : 0;
    $tag['status'] = isset($tag['status']) ? trim($tag['status']) : 0;
    $tag['status_type'] = isset($tag['status_type']) ? trim($tag['status_type']) : 0;
    $tag['exceptid'] = isset($tag['exceptid']) ? trim($tag['exceptid']) : 0;//除了哪个文档不显示

    /*
     * how表示选择什么类型的文档，如down表示下载数最多
     * rate评分排行,wytj表示网友推荐的,wysc网友收藏
     *
     * search如果有值，表示按照关键字去查询
     * similar如果有值，说明查找该id的相关文档
     *
     */

    $doc_mod = Db::name('doc_con');
    $select = $doc_mod->field($tag['field']); //字段
    $where[] = array('del_status', '=', 1);//未删除
//    $where[] = array('convert_status', '=', 2);//已转换
//        $where[] = array('status', '=', 1);//已审核
     //条件
     if ($tag['exceptid']) {
         $where[] = array('id', '<>', $tag['exceptid']);
     }
     if ($tag['ext']) {
         $where[] = array('ext', 'in', $tag['ext']);
     }

     if ($tag['uid']) {
         if ($tag['own']) {
             $where[] = array('uid', '=', $tag['uid']);
         } elseif ($tag['usertype']) {
             switch ($tag['usertype']) {
                 case 'down':
                     $idarr = useritemid($tag['uid'], 1,1);
                     break;
                 case 'wysc':
                     $idarr = useritemid($tag['uid'], 1,2);
                     break;
                 default:
                     break;
             }
             $where[] = array('id', 'in', $idarr);
         }
     }
     $now = time();
     if ($tag['day']) {//如果填写了天数，表示查找该范围内的文档
         $where[] = array('create_time', '>=', $now - $tag['day'] * 24 * 3600);
     } else {
         $where[] = array('create_time', '<=', $now - $tag['cache']);
     }
     if ($tag['cateid']) {//如果填写了，表示查找该分类范围内的文档，可以为1,2,3,4用半角逗号隔开
         $where[] = array('cid', 'in', $tag['cateid']);
     }
     if ($tag['status']) {
         $where[] = array('status', '=', $tag['status']);
     }
     if ($tag['status_type']) {
         $where[] = array('status', '=',0);
     }else{
         $where[] = array('status', '=',1);
     }
     if ($tag['choice']) {
         $where[] = array('choice', '=', $tag['choice']);
     }
     if ($tag['top']) {
         $where[] = array('top', '=', $tag['top']);
     }

     if ($tag['minscore'] != 'min') {
         $where[] = array('score', '>=', $tag['minscore']);
         if ($tag['maxscore'] != 'max') {
             if ($tag['maxscore'] > $tag['minscore']) {
                 $where[] = array('score', 'between', array($tag['minscore'], $tag['maxscore']));
             }
         }
     } else {
         if ($tag['maxscore'] != 'max') {
             $where[] = array('score', '<=', $tag['maxscore']);
         }
     }

     if ($tag['search']) {
         $searcharr = explode(',', $tag['search']);
//        delete_empty($searcharr);
         foreach ($searcharr as $keysear => $valuesear) {
//                $searcharr[$keysear] = '%' . $valuesear . '%';
             $where[] = array('tags|title', 'like', '%' . $valuesear . '%');
         }
     }
     if ($tag['similar']) {
         $tags = Db::name('doc_con')->where('id',$tag['similar'])->value('tags');
         $tagarr = explode(',', $tags);
         foreach ($tagarr as $key => $value) {
//                $tagarr[$key] = '%' . $value . '%';
             $where[] = array('tags|title', 'like','%' . $value . '%');
         }
     }

     if ($tag['pagenum']) {
         $count = $select->where($where)->count();// 查询满足要求的总记录数
         $Page = new \think\Page($count, $tag['pagenum']);// 实例化分页类 传入总记录数和每页显示的记录数
         $data['page'] = $Page->show();// 分页显示输出
         $data['total'] = $count;
         $aa = $select->where($where)->order($tag['order'])->limit($Page->firstRow, $Page->listRows)->fetchSql(true)->select();
//         var_dump($aa); exit;
     } else {
         $select->where($where);
         $select->order($tag['order']); //排序
     }
     $data['list'] = $select->select()->toArray();
     foreach ($data['list'] as $key => $value) {
         $data['list'][$key]['downnum'] = downcount($value['id'], 1);
         $data['list'][$key]['wyscnum'] = wysccount($value['id'], 1);
         $data['list'][$key]['wytjnum'] = wytjcount($value['id'], 1);
     }
     if ($tag['how'] != '') {
         switch ($tag['how']) {
             case 'down':
                 foreach ($data['list'] as $key => $value) {
                     $data['list'][$key]['comcount'] = downcount($value['id'], 1);
                 }
                 usort($data['list'], 'cmpcomcount');
                 break;
             case 'rate':
                 foreach ($data['list'] as $key => $value) {
                     $data['list'][$key]['comcount'] = getraty($value['id'], 1);
                 }
                 usort($data['list'], 'cmpcomcount');
                 break;
             case 'wytj':
                 foreach ($data['list'] as $key => $value) {
                     $data['list'][$key]['comcount'] = wytjcount($value['id'], 1);
                 }
                 usort($data['list'], 'cmpcomcount');
                 break;
             case 'wysc':
                 foreach ($data['list'] as $key => $value) {
                     $data['list'][$key]['comcount'] = wysccount($value['id'], 1);
                 }
                 usort($data['list'], 'cmpcomcount');
                 break;
             case 'comment':
                 foreach ($data['list'] as $key => $value) {
                     $data['list'][$key]['comcount'] = comcount($value['id'], 1);
                 }
                 usort($data['list'], 'cmpcomcount');
                 break;
             default:
                 break;
         }
     }
     return $data;
 }


// 获得专辑下文档数量 -- wf添加 --rabin废弃
function doccount($zjid) { //用户下载数
    $where[] = array('zjid','=',$zjid);
    $where[] = array('status','>',0);
    $data = Db::name('doc_con')->where($where)->count();
    return $data;
}


function getisadmin($roleid) {
    $where[] = array('id','=',$roleid);
    $where[] = array('status','=',1);
    $data = Db::name('user_role')->where($where)->value('isAdmin');
    if ($data == 1) {
        return true;
    } else {
        return false;
    }
}

//编辑推荐文档
function tjdoc() {
    //$map['id']=$id;
    //$map1['cateid']=$this->_mod->where($map)->getField('cateid');
    $map['status'] = 4;
    $data = Db::name('doc_con')->where($map)->select();
    return $data;
}


//新的面包屑 -wfgo
function getnavlist($id=0,$modulename,$actionname) {
    $url=url($modulename.'/'.$actionname);
    $html = '';
    switch ($modulename){
        case 'doc':
            $modulename = '文档';
            switch ($actionname){
                case 'doccate':
                    $actionnameview='全部分类';
                    $html='<a href="'.$url.'">'.$actionnameview.'</a>';
                    break;

                case 'doclist':
                    $actionnameview='全部文档';
                    $html='<a href="">'.$actionnameview.'</a>';
                    if ($id) {
                        $url=url($modulename.'/'.$actionname,array('id'=>$id));
                        $actionnameview=Db::name('category')->where(array('id'=>$id,'status'=>'1'))->value('name');
                        if ($actionnameview == '') {
                            $data = '待定分类';
                        }
                        $html='<a href="'.$url.'">'.$actionnameview.'</a>';
                    }
                    break;

                case 'doccon':
                    if ($id) {
                        $docname=Db::name('doc_con')->where(array('id'=>$id))->field('title,cid')->find();
                        $ctname=Db::name('category')->where(array('id'=>$docname['cid']))->value('name');
                        $cturl=url('doc/doclist',array('id'=>$docname['cid']));
                        if ($docname == '') {
                            $data = '暂无标题';
                        }
                        $html='<a href="'.$cturl.'">'.$ctname.'</a><a>'.$docname['title'].'</a>';
                    }
                    break;
            }
            break;
        case 'album':
            $modulename='专辑';
            if ($actionname == 'zjinfo') {
                $zjlisturl=url('album/index');
                $zjname=Db::name('album')->where(array('id'=>$id))->value('title');
                $html='<a href="'.$zjlisturl.'">'.$modulename.'</a><a>'.$zjname.'</a>';
            }else{
                $html='<a href="">'.$modulename.'</a>';
            }
            break;
        case 'ucenter':
            $modulename='用户中心';
            $html='<a href="">'.$modulename.'</a>';
            break;
        default:
            $modulename = '';
            break;
    }

    return $html;
}


function getrolename($id) {
    $map['id'] = $id;
    $dataid = Db::name('user')->where($map)->value('roleid');
    $map1['id'] = $dataid;
    $data = Db::name('user_role')->where($map1)->value('name');
    return $data;
}



function msubstr($str, $length, $start=0, $suffix=false,$charset="utf-8"){
    if(function_exists("mb_substr")){
        $slice=mb_substr($str, $start, $length, $charset);
        if($suffix){
            if(mb_strlen($str,'utf-8')>$length){
                return $slice."...";
            }else{
                return $slice;
            }
        }else{
            return $slice;
        }
    }elseif(function_exists('iconv_substr')){
        if($suffix){
            return iconv_substr($str,$start,$length,$charset)."...";
        }else{
            return iconv_substr($str,$start,$length,$charset);
        }
    }

    $re['utf-8'] = "/[x01-x7f]|[xc2-xdf][x80-xbf]|[xe0-xef][x80-xbf]{2}|[xf0-xff][x80-xbf]{3}/";
    $re['gb2312'] = "/[x01-x7f]|[xb0-xf7][xa0-xfe]/";
    $re['gbk'] = "/[x01-x7f]|[x81-xfe][x40-xfe]/";
    $re['big5'] = "/[x01-x7f]|[x81-xfe]([x40-x7e]|xa1-xfe])/";
    preg_match_all($re[$charset], $str, $match);
    $slice = join("",array_slice($match[0], $start, $length));
    if($suffix) {
        if(strlen($slice)>$length){
            return $slice."…";
        }else{
            return $slice;
        }
    }
    return $slice;
}

//新的获取数据库中的用户头像方法
function getavatar($uid) {
    $data = Db::name('user')->where(array('id' => $uid))->value('avatar');
    if (!$data) {
        $data = 'data/upload/avatar/default_160.jpg';
    }
    $data .= '?v=' . time();
    return $data;
}

/**
 * 字节格式化 把字节数格式为 B K M G T 描述的大小
 * @return string
 */
function byte_format($size, $dec=2) {
    $a = array("B", "KB", "MB", "GB", "TB", "PB");
    $pos = 0;
    while ($size >= 1024) {
        $size /= 1024;
        $pos++;
    }
    return round($size,$dec)." ".$a[$pos];
}

/*增加和减少用户积分
 * $add为1表示增加，0表示减少
 * scoretype表示操作字段
 *
 *
 * */
function opuserscore($uid, $add, $scoretype, $score) {
    if (is_array($uid)) {
        $map['uid'] = array('in', $uid);
        foreach ($uid as $key => $value) {
            $map1['uid'] = $value;
            if (Db::name('user_scoresum')->where($map1)->find() == null) {
                Db::name('user_scoresum')->save($map1);
            }
        }
    } else {
        $map['uid'] = $uid;
        if (Db::name('user_scoresum')->where($map)->find() == null) {
            Db::name('user_scoresum')->save($map);
        }
    }
    if ($add) {
        if (Db::name('user_scoresum')->where($map)->inc($scoretype, $score)) {
            return 1;
        } else {
            return 0;
        }
    } else {
        if (Db::name('user_scoresum')->where($map)->dec($scoretype, $score)) {
            return 1;
        } else {
            return 0;
        }
    }
}

function ad_store($id){
    return app('app\home\controller\Advert')->getAd($id);
}

function getcatename($type, $id) {
    $mod = Db::name('category');
    $map['id'] = $id;
    $map['status'] = 1;
    $data = $mod->where($map)->value('name');
    if ($data == '') {
        $data = '待定分类';
    }
    return $data;
}

function doc_title_exists($title){
    $data = Db::name('doc_con')->where('title',$title)->count();
    return $data >0?true:false;
}

function getsearchtitle($searchword, $title) {
    $searcharr = explode(' ', $searchword);
//    delete_empty($searcharr);
    foreach ($searcharr as $key => $value) {
        $title = str_replace($value, '<font color=red><b>' . $value . '</b></font>', $title);
    }
    return $title;
}